const {BASE_URL} = require('./setting')

class Request {
  constructor(data) {
    this.baseUrl = data.baseUrl
    this.withBaseUrl = data.withBaseUrl || true
    this.queue = {}
  }

  request(options) {
    const { method, url, data = {}, header = {}, callback } = options
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token') || null
      this.queue[url] = wx.request({
        url: this.withBaseUrl ? `${this.baseUrl}${url}` : url,
        data: Object.assign({ wxapp_id: 10001, token }, data || {}),
        header: Object.assign({'Content-Type':'application/json'}, header),
        method: method.toUpperCase(),
        dataType: 'json',
        responseType: 'text',
        timeout: 10000,
        success: (result)=>{
          resolve(result.data)
        },
        fail: (error)=>{
          if (error.errMsg !== 'request:fail abort') {
            wx.showToast({ title: '网络错误，请稍后再试', icon: 'none', duration: 1500 })
          }
          reject({
            msg: '请求失败',
            url: this.baseUrl + url,
            method,
            data,
            error
          })
        },
        complete: ()=>{
          delete this.queue[url]
          callback && callback()
        }
      })
    })
  }

  get(options) {
    options = Object.assign({ method: 'GET' }, options)
    return this.request(options)
  }

  post(options) {
    options = Object.assign({ method: 'POST'}, options )
    return this.request(options)
  }
}

module.exports = {
  Request,
  wxRequest: () => new Request({ widthBaseUrl: true, baseUrl: BASE_URL })
}
